package com.code.javaconcurrent;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/7/15 16:30
 * @see java concurrency in Practice P83 5-14
 */

public class BoundedHashSet<T> {

    private final Set<T> set;
    private final Semaphore semaphore;

    public BoundedHashSet(int bound) {
        set = Collections.synchronizedSet(new HashSet<>());
        semaphore = new Semaphore(bound);
    }

    public boolean add(T o) throws InterruptedException {
        semaphore.acquire();
        boolean flag = false;
        try {
            flag =  set.add(o);
            return flag;
        } finally {
            if (!flag) {
                semaphore.release();
            }
        }
    }

    public boolean remove(Object o) {
        boolean remove = set.remove(o);
        if (remove) {
            semaphore.release();
        }
        return remove;
    }

}
